﻿// CLoginDialog.cpp: 实现文件
//

#include "pch.h"
#include "HotelManagementMFC.h"
#include "afxdialogex.h"
#include "CLoginDialog.h"


// CLoginDialog 对话框

IMPLEMENT_DYNAMIC(CLoginDialog, CDialog)

CLoginDialog::CLoginDialog(CWnd* pParent /*=nullptr*/)
	: CDialog(IDD_DLG_LOGIN, pParent)
{

}

CLoginDialog::~CLoginDialog()
{
}

void CLoginDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_USERNAME, m_sUserName);
	DDX_Control(pDX, IDC_PASSWD, m_sPasswd);
}


BEGIN_MESSAGE_MAP(CLoginDialog, CDialog)
	ON_BN_CLICKED(IDOK, &CLoginDialog::OnBnClickedOk)
	ON_BN_CLICKED(IDCANCEL, &CLoginDialog::OnBnClickedCancel)
END_MESSAGE_MAP()


// CLoginDialog 消息处理程序


/// <summary>
/// 确认登录
/// </summary>
void CLoginDialog::OnBnClickedOk()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(1);
	CString m_username, m_passwd;
	m_sUserName.GetWindowTextW(m_username);
	m_sPasswd.GetWindowTextW(m_passwd);

	CString db_name, db_passwd, db_type;
	// 查询字符串
	CString strSQL;
	strSQL.Format(L"Select Name, Password, Type From user Where Name = '%s' And Password = '%s'", m_username, m_passwd);
	// 查询过程
	try {
		m_pRecordSet.CreateInstance(__uuidof(Recordset));
		// 根据连接字符串开启连接，获取结果集
		m_pRecordSet->Open(strSQL.AllocSysString(),
			theApp.m_pConnection.GetInterfacePtr(),
			adOpenDynamic,
			adLockOptimistic,
			adCmdText);

		// 获取记录值
		_variant_t Holder;
		if (m_pRecordSet->RecordCount != 0)
		{
			theApp.m_GetCollect(m_pRecordSet, Holder, db_name, "Name");
			theApp.m_GetCollect(m_pRecordSet, Holder, db_passwd, "Password");
			theApp.m_GetCollect(m_pRecordSet, Holder, db_type, "Type");
		}
	}
	catch (_com_error* e)
	{
		AfxMessageBox(e->Description());
	}

	// 验证
	if (m_username.CompareNoCase(db_name) == 0 && m_passwd.CompareNoCase(db_passwd) == 0)
	{
		MessageBox(L"登录合法 : " + db_name, L"登录", MB_OK);
		CDialog::OnOK();
		if (db_type == "A" || db_type == "a")
			theApp.nFlag = TRUE;
		else
			theApp.nFlag = FALSE;
	}
	else
	{
		if (MessageBoxW(L"登录失败", L"账户名或密码错误", MB_RETRYCANCEL) == IDRETRY)
		{
			m_sUserName.SetWindowTextW(L"");
			m_sPasswd.SetWindowTextW(L"");
		}
		else
		{
			EndDialog(IDCANCEL);
			AfxGetMainWnd()->PostMessageW(WM_QUIT);
		}
	}
}


/// <summary>
/// 取消登录
/// </summary>
void CLoginDialog::OnBnClickedCancel()
{
	// TODO: 在此添加控件通知处理程序代码
	EndDialog(IDCANCEL);
	AfxGetMainWnd()->PostMessageW(WM_QUIT);
	//CDialog::OnCancel();
}
